package edu.seu.mart.service;

import com.alibaba.fastjson.JSONObject;
import edu.seu.mart.model.Article;
import edu.seu.mart.model.MsgType;
import edu.seu.mart.model.NewsMsg;
import edu.seu.mart.model.TextMsg;
import edu.seu.mart.utils.MsgKit;
import edu.seu.mart.utils.TulingKit;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 图灵机器人API处理类
 */
public class TulingService {
    /**
     * 图灵API开发者账号
     */
    private static final String APIKEY = "ba5db58407613b7814cd2339daa91b4e";
    /**
     * 图灵API请求URL地址
     */
    private static final String TLURL = "http://www.tuling123.com/openapi/api?key=" + APIKEY + "&info=";

    /**
     * 用户文本消息，调用图灵API，返回JSON数据格式结果
     * @param info
     */
    public String getTulingJson(String info) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(TLURL + info);
        CloseableHttpResponse response = null;
        String json = null;
        try {
            response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode >= 200 && statusCode < 300) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    json = EntityUtils.toString(entity);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return json;
    }

    public String tlRespMsg(String info, String fromUserName, String toUserName) {
        String json = this.getTulingJson(info);
        // 如果为空，直接返回空字符串
        if (json == null) {
            return "";
        }
        JSONObject object = JSONObject.parseObject(json);
        String code = object.getString("code");
        // 如果是新闻或者火车，则返回图文消息
        if (code.equals("302000") || code.equals("305000")) {
            NewsMsg newsMsg = new NewsMsg();
            newsMsg.setToUserName(fromUserName);
            newsMsg.setFromUserName(toUserName);
            newsMsg.setCreateTime(new Date().getTime());
            newsMsg.setMsgType(MsgType.NEWS.getName());
            List<Article> articles = TulingKit.respNews(object, code);
            newsMsg.setArticleCount(articles.size());
            newsMsg.setAirticles(articles);
            return MsgKit.newsMsgToXml(newsMsg);
        } else {
            // 其他情况，返回文本消息
            TextMsg textMsg = new TextMsg();
            textMsg.setToUserName(fromUserName);
            textMsg.setFromUserName(toUserName);
            textMsg.setCreateTime(new Date().getTime());
            textMsg.setMsgType(MsgType.TEXT.getName());
            String content = "亲，我玩累啦，明天再来找我玩吧！" +
                    "请访问我们的官网：http://allsky.nat123.net/MicroMart/weixin/";
            // 如果code长度为5，则说明图灵机器人API返回异常
            if (code.length() != 5) {
                content = TulingKit.respText(object, code);
            }
            textMsg.setContent(content);
            return MsgKit.textMsgToXml(textMsg);
        }
    }
}
